<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 企业首页相关Controller v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\controller\enterprise;

use app\core\model\CacheKey;
use app\core\model\Enterprise;
use app\core\model\EnterpriseModule;
use app\core\model\SiteModuleConfig;
use app\core\model\SiteModuleWidget;

class IndexController extends EnterpriseBaseController {
//    protected function _checkLogin() {
//        $action = strtolower($this->request->action());
//        if ($action == 'index') {
//            $code = input("get.code");
//            if (empty($code)) {
//                return parent::_checkLogin();
//            } else {
//                $eid = input("get.eid");
//                $loginUrl = '/core/enterprise.user/dingAdminAuth?eid=' . $eid . "&code=" . $code;
//                throw new HttpResponseException(
//                    redirect($loginUrl)
//                );
//            }
//        } else {
//            return parent::_checkLogin();
//        }
//    }

    /**
     * 后台首页
     *
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index() {
        $homePage = Enterprise::parseHomepage($this->enterprise);

        $homePageUrl = false;
        if ($this->env['dingMobile']) {
            //钉钉手机端
            $homePageUrl = fetch(
                $homePage,
                'dingMobile',
                '/core/enterprise.index/microapp',
                true
            );
        } else if ($this->env['dingPc']) {
            //钉钉PC端在浏览器中打开
            $redirectUrl = urlencode($this->request->url(true));
            $homePageUrl = fetch(
                $homePage,
                'dingPc',
                "/index/index/jump?from=dingPc&to=browser&url=" . $redirectUrl,
                true
            );
        } else if ($this->env['mobile']) {
            //手机页面
            $homePageUrl = fetch(
                $homePage,
                'mobile',
                false,
                true
            );
        } else {
            //PC页面
            $homePageUrl = fetch(
                $homePage,
                'pc',
                false,
                true
            );
        }

        if ($homePageUrl) {
            if (strpos($homePageUrl, '?') !== FALSE) {
                $homePageUrl .= "&";
            } else {
                $homePageUrl .= "?";
            }
            $homePageUrl .= "eid=" . $this->eid;
            $this->redirect($homePageUrl);
        }

        $this->assign("indexUrl", "/core/enterprise");
        $this->assign("logoutUrl", "/core/enterprise/logout?eid=" . $this->eid);
        $this->assign("userAvatar", $this->user['avatar']);
        $this->assign("userName", $this->user['showname']);
        $this->assign("menus", $this->_getMenus());
        $this->assign("userMenus", $this->_getUserMenus());
        return view();
    }

    /**
     * 获取用户下拉菜单
     *
     * @return array
     */
    private function _getUserMenus() {
        $userMenus = [];
        array_push($userMenus, [
            'title' => '账号编辑',
            'link' => '/core/enterprise.user/profile'
        ]);

        if ($this->_isEnterpriseAdmin()) {
            array_push($userMenus, [
                'title' => '自定义配置',
                'link' => '/core/enterprise.customize/index'
            ]);
            array_push($userMenus, [
                'title' => '企业信息配置',
                'link' => '/core/enterprise.info/config'
            ]);
            if (!empty($this->enterprise['corpid'])) {
                array_push($userMenus, [
                    'title' => '钉钉回调设置',
                    'link' => '/core/enterprise.info/callback'
                ]);
            }
            array_push($userMenus, [
                'title' => '组织管理',
                'link' => '/core/enterprise.org.index/index'
            ]);
        }

        return $userMenus;
    }

    /**
     * 获取菜单
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function _getMenus() {
        $cacheKey = CacheKey::module("core")->type("enterprise.menus")->tags([
            'eid' => $this->eid,
            'userid' => $this->userid
        ]);
        $menus = $cacheKey->getValue();
        if (!empty($menus)) {
            return $menus;
        }
        $menus = [];

        $allModuleWidgets = $this->_getHomeWidgets();
        if (count($allModuleWidgets) > 0) {
            $menus[] = [
                'title' => $this->enterprise['title'],
                'link' => '/core/enterprise.index/home?eid=' . $this->eid
            ];
        }

        $enterpriseModules = $this->_getModuleList();
        foreach ($enterpriseModules as $enterpriseModule) {
            $module = $enterpriseModule['module'];
            if (!$module) {
                continue;
            }
            $mid = $module['id'];

            $widgets = SiteModuleWidget::getWidgets($mid);
            $moduleMenus = EnterpriseModule::getModuleMenus($mid);

            if (empty($widgets) && empty($moduleMenus)) {
                //如果没有设置挂件，并且没有设置左侧菜单，则顶部菜单不显示
                continue;
            }

            $menu = [];
            $menu['title'] = $module['title'];
            $menu['attr'] = ["mid" => $mid];
            $menu['link'] = empty($widgets) ? "" : ('/core/enterprise.module/home?mid=' . $mid . '&eid=' . $this->eid);
            $menu['left'] = [];

            foreach ($moduleMenus as $moduleMenu) {
                if ($moduleMenu['authority'] && !$this->_hasModuleAuthority($mid, $moduleMenu['authority'])) {
                    continue;
                }
                $menu['left'][] = [
                    'title' => $moduleMenu['title'],
                    'link' => $moduleMenu['link'],
                    'sub' => fetch($moduleMenu, "sub", [])
                ];
            }

            if ($this->_isModuleAdmin($mid) || $this->_isEnterpriseAdmin()) {
                $sub = [];
                //模块设置项
                $configs = SiteModuleConfig::getConfigs($mid);
                if (!empty($configs)) {
                    $sub[] = [
                        'title' => '模块基础设置',
                        'link' => '/core/enterprise.module/config?mid=' . $mid
                    ];
                }
                //功能权限设置
                $sub[] = [
                    'title' => '功能权限设置',
                    'link' => '/core/enterprise.module/authoritySetting?mid=' . $mid
                ];
                if (!empty($this->enterprise['corpid'])) {
                    //钉钉API权限设置
                    $sub[] = [
                        'title' => 'API权限设置',
                        'link' => '/core/enterprise.module/apiSetting?mid=' . $mid
                    ];
                }
                $menu['left'][] = [
                    'title' => "模块设置",
                    'sub' => $sub
                ];
            }

            if (empty($menu['left'])) {
                continue;
            }

            $menus[] = $menu;
        }

        $cacheKey->setValue($menus);
        return $menus;
    }

    /**
     * 企业首页
     *
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function home() {
        $allModuleWidgets = $this->_getHomeWidgets();
        $this->assign("allModuleWidgets", $allModuleWidgets);
        return view();
    }

    /**
     * 全局微应用
     *
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function microapp() {
        $moduleName = input("get.module");
        $modules = [];
        $enterpriseModules = $this->_getModuleList();
        foreach ($enterpriseModules as $enterpriseModule) {
            $module = $enterpriseModule['module'];
            if (!$module) {
                continue;
            }
            if ($moduleName && $module['name'] != $moduleName) {
                continue;
            }
            $entries = EnterpriseModule::getModuleEntries($module['id'], $this->eid);
            if (empty($entries)) {
                continue;
            }
            $module['entries'] = $entries;
            $modules[] = $module;
        }

        $this->assign("modules", $modules);
        return view();
    }

    /**
     * 获取当前用户能够访问到的模块列表
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function _getModuleList() {
        $enterpriseModules = EnterpriseModule::listAll($this->eid);

        $showEnterpriseModules = [];
        // 筛选出当前登录人员可以看到的模块
        foreach ($enterpriseModules as &$enterpriseModule) {
            if ($enterpriseModule['status'] != EnterpriseModule::ENTERPRISE_MODULE_STATUS_NORMAL) {
                continue;
            }

            if ($this->_canAccessModule($enterpriseModule)) {
                $showEnterpriseModules[] = $enterpriseModule;
            }
        }

        return $showEnterpriseModules;
    }

    /**
     * 获取在首页展示的挂件
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function _getHomeWidgets() {
        $allModuleWidgets = [];
        $enterpriseModules = $this->_getModuleList();
        foreach ($enterpriseModules as $enterpriseModule) {
            $module = $enterpriseModule['module'];
            if (!$module) {
                continue;
            }
            $moduleWidgetInfos = $this->_getWidgetInfos($module, "global");
            if (empty($moduleWidgetInfos)) {
                continue;
            }
            $allModuleWidgets[] = [
                'module' => $module,
                'widgets' => $moduleWidgetInfos
            ];
        }
        return $allModuleWidgets;
    }
}
